<template>
  <el-dialog v-model="dialog.visible" title="审核" width="45%" @close="handleCloseDialog">
    <div class="form-container" v-loading="loading">
      <el-form
        ref="baseFormRef"
        :model="formData"
        :rules="formRules"
        label-width="150px"
        class="form mb-0"
      >
        <el-form-item label="审核理由">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入理由"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          icon="check"
          :loading="auditLoading"
          @click="handleAudit(formData.id, '通过', ACTIVITY_STATUS_ENUM.NOT_STARTED.value)"
        >
          通过
        </el-button>
        <el-button
          type="danger"
          icon="close"
          :loading="auditLoading"
          @click="handleAudit(formData.id, '驳回', ACTIVITY_STATUS_ENUM.REJECTED.value)"
        >
          驳回
        </el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import ActivityAPI, { SysMerchantActivityForm } from "@/api/operationManage/activity";
import { ACTIVITY_STATUS_ENUM } from "@/enums/operationManage/ActivityEnum";

// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData"]);
const dialog = reactive({
  title: "",
  visible: false,
});
/*基础信息*/
const baseFormRef = ref();
const currentRow = ref({});
const loading = ref(false);
const auditLoading = ref(false);

const defaultFormData: SysMerchantActivityForm = {
  content: "",
  endTime: "",
  id: undefined,
  images: [],
  name: "",
  remark: "",
  startTime: "",
  state: undefined,
  title: "",
};
const formData = ref({
  ...defaultFormData,
});
const formRules = reactive({
  content: [{ required: true, message: "请输入活动内容", trigger: "blur" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  title: [{ required: true, message: "请输入副标题", trigger: "blur" }],
  images: [{ required: true, message: "请上传活动图片", trigger: "change" }],
  startTime: [
    { required: true, message: "请选择开始时间", trigger: "change" },
    {
      validator: (rule, value) => value <= formData.value.endTime,
      trigger: "change",
      message: "开始时间不能大于结束时间",
    },
  ],
  endTime: [
    { required: true, message: "请选择结束时间", trigger: "change" },
    {
      validator: (rule, value) => value >= formData.value.startTime,
      message: "结束时间不能小于开始时间",
    },
  ],
});

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formData.value = {};
  Object.assign(formData.value, JSON.parse(JSON.stringify(defaultFormData)));
  emit("update:modelValue", false); // 关闭弹窗
}

function showModal(val) {
  dialog.visible = true;
  currentRow.value = val;
  if (val) {
    getDetailById(val.id);
  } else {
    Object.assign(formData.value, JSON.parse(JSON.stringify(defaultFormData)));
  }
}

async function handleAudit(id, desc, state) {
  const result = await ElMessageBox.confirm(`确认${desc}吗?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  if (!result) return;
  try {
    auditLoading.value = true;
    await ActivityAPI.audit({
      id: id,
      state,
      remark: formData.value.remark,
    });
    ElMessage.success(`${desc}成功`);
    emit("loadData");
    handleCloseDialog();
  } catch (e) {
    console.log(e);
  } finally {
    auditLoading.value = false;
  }
}

async function getDetailById(id) {
  try {
    loading.value = true;
    const data = await ActivityAPI.getDetailById({
      id,
    });
    const { images } = data || {};
    formData.value = {
      ...formData.value,
      ...defaultFormData,
      ...data,
      ...{
        images: JSON.parse(images || "[]"),
      },
    };
  } catch (e) {
    console.log(e);
  } finally {
    loading.value = false;
  }
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
.form-container {
  height: 400px;
  overflow: auto;
}
.form {
  ::v-deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
